//
//  LWHomeViewModel.swift
//  Microblog
//
//  Created by Roman on 17/1/9.
//  Copyright © 2017年 Roman. All rights reserved.
//

import UIKit
import SDWebImage

class LWHomeViewModel: NSObject {
    
    
    lazy var viewmodelArray:[LWHomeCellModel] = [LWHomeCellModel]()
    
    //进行数据的加载
    //封装一个加载数据的接口, 值关注成功和失败
    func loadDate(isPullUp: Bool,finished : @escaping (Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let access_token = LWUserAccountViewModel.shard.access_token else{
            
            return
        }
        print(access_token)
        
        //加载更多数据
        var parameters = ["access_token":access_token]
        
        if isPullUp {
            let maxid = self.viewmodelArray.last?.statuses?.id ?? 0
            if maxid > 0 {
                
                parameters["max_id"] = "\(maxid - 1)"
            }
        }
        
        
        print(parameters)
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (response, error) in
            if error != nil {
                finished(false)
               
                return
            }
            let dict = response as! [String : Any]
            
            //转换成字典类型数组
            let array = dict["statuses"] as! [[String : Any]]
            
            var tempArray = [LWHomeCellModel]()
            //遍历数组,字典转模型
            for item in array{
                //实例化cell的视图模型
                let cellModel = LWHomeCellModel()
                let a = LWstatusesModel()
                // a.text = item["text"] as? String
                //使用YYmodel 来进行字典转模型
                a.yy_modelSet(with: item)
                cellModel.statuses = a
                //添加到临时的数组中
                tempArray.append(cellModel)
            }
            //记录临时数组
            //判断,如果是上拉,就要加载更多数据
            if isPullUp {
                //上拉加载更多数据
                self.viewmodelArray =  self.viewmodelArray + tempArray
                
            }else{
                
                self.viewmodelArray = tempArray
            }
//            //成功的回调
//            finished(true)
           self.cacheSingleStatusImage(array: tempArray, downloadFinished: finished)
        }
    }
    private func cacheSingleStatusImage(array: [LWHomeCellModel], downloadFinished: @escaping (Bool) -> ()) {
        
        //下载单张图片, 先判断是否是单张图片
        if array.count == 0 {
            downloadFinished(true)
            return
        }
        //定义调度组
        let group = DispatchGroup()
        //调度组
        for viewmodel in array {
            if viewmodel.imageType?.count == 1{
                //单张图片执行下载任务
                let url = URL(string: viewmodel.imageType?.first?.wap360 ?? "")
                group.enter() //调度组任务➕1
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    //这里不能执行成功的回调
                   // downloadFinished(true)
                    print("单张图片下载完毕")
                    group.leave() //调度组任务减1
                })
            }
        }
        
        //等所有图片下载完毕后执行成功的回调
        group.notify(queue: DispatchQueue.main, execute:
            {
                print("所有图片下载完毕")
                //执行回调
                downloadFinished(true)
        })
        
        
        
        
        
    }
  

}
